package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.adapter.CardAccountListAdapter;
import com.kuanter.kuanterauto.adapter.CardAndNumberImageAdapter;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.CardInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.kuanter.kuanterauto.utils.UtilListView;
import com.kuanter.kuanterauto.view.MyGallery;
import com.umeng.analytics.MobclickAgent;

public class CardAndAccountActivity extends BaseActivity_NoBar {
	private static final int RECHARGE = 0;
	private MyGallery gallery;
	private List<CardInfo> cardInfos;
	private DataLoader dataLoader;
	private String userId;
	private TextView card_number_tv;
	private ListView lv_cardInfoList;
	protected CardAndNumberImageAdapter cardAndNumberImageAdapter;
	public static int flag = 0 ;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
//				String result = msg.getData().getString("result");
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
															// 字段值是否为false
							com.alibaba.fastjson.JSONObject jsonObjectResult = JSON
									.parseObject(result);
							if(null != jsonObjectResult
									.getString("cardInfoList")){
								String JsonStringUserInfo = jsonObjectResult
										.getString("cardInfoList");
								cardInfos = JSON.parseArray(
										JsonStringUserInfo, CardInfo.class);
								
								// 将cardInfoList缓存
								ObjectCache.set("cardInfoList", cardInfos);
								application = (ProApplication)getApplication();
								application.setCardInfoList(cardInfos);
								gallery = (MyGallery) CardAndAccountActivity.this.findViewById(R.id.gallery);
								gallery.setSpacing(10);
								cardAndNumberImageAdapter = new CardAndNumberImageAdapter(cardInfos,CardAndAccountActivity.this);
								gallery.setAdapter(cardAndNumberImageAdapter);
								gallery.setOnItemSelectedListener(new MyOnItemSelectedListener());
							}
							finishProgress();
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							showToast("失败");
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("登录失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	
	Handler handler2 = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
//				String result = msg.getData().getString("result");
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
															// 字段值是否为false
								showToast("挂失成功");
								/*for(CardInfo cardInfo : cardInfos){
									if(card_number == cardInfo.getCardNumber()){
										cardInfo.setState("3");
									}
									application.setCardInfoList(cardInfos);
								}*/
								CardAndAccountActivity.this.downLoadCardInfos();
								flag = 200 ;
							finishProgress();
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							showToast("失败");
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("登录失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	private ListView card_account_list;
	private String card_number;
	private CardInfo cardInfo;
	private Button back_btn;
	private Button reissue_card_goto;
	private Button recharge_goto;
	private View view;
	private ProApplication application;
	private String chooseed_credits;
	private RelativeLayout rl_recharge_goto;
	private RelativeLayout rl_reissue_card_goto;
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if(200 == flag){
			downLoadCardInfos();
			flag = 0;
		}
		super.onResume();
		 MobclickAgent.onResume(this);
	}
	
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.card_and_account);
		application = (ProApplication)getApplication();
		//返回
		back_btn = (Button)this.findViewById(R.id.back_btn);
		back_btn.setOnClickListener(this);
		//挂失
		rl_reissue_card_goto = (RelativeLayout)this.findViewById(R.id.rl_reissue_card_goto);
		reissue_card_goto = (Button)this.findViewById(R.id.reissue_card_goto);
		reissue_card_goto.setOnClickListener(this);
		//充值
		rl_recharge_goto = (RelativeLayout)this.findViewById(R.id.rl_recharge_goto);
		recharge_goto  = (Button)this.findViewById(R.id.recharge_goto);
		recharge_goto.setOnClickListener(this);
		SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
		userId = sp.getString("id", "000") ;
		if(null == application.getCardInfoList()||application.getCardInfoList().size()==0){
			this.downLoadCardInfos();
		}else {
			gallery = (MyGallery) CardAndAccountActivity.this.findViewById(R.id.gallery);
			gallery.setSpacing(10);
			gallery.setAdapter(new CardAndNumberImageAdapter(application.getCardInfoList(),CardAndAccountActivity.this));
			gallery.setOnItemSelectedListener(new MyOnItemSelectedListener());
		}
	}

	private void downLoadCardInfos() {
		dataLoader = new DataLoader(this);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		//从SharedPreferences本地化数据中区账号信息
		
		params.add(new BasicNameValuePair("cardInfo.userId",userId));
		dataLoader.DisplayData(MainConstants.HOST_test
				+ HttpConfigAPI.QUERY_CARD, params, handler, "", false);
		showProgress("正在加载数据...");
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_btn:
			this.finish();
			break;
		case R.id.reissue_card_goto:
			//模拟打电话
			//showToast("模拟打电话");
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("确认挂失卡号");
//			view = View.inflate(this, R.layout.edit, null);
//			builder.setView(view);
			builder.setMessage(card_number);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0,
								int arg1) {
							if(null != cardInfos){
								for(CardInfo cardInfo : cardInfos){
									if(card_number == cardInfo.getCardNumber()){
										if("2".equals(cardInfo.getState())){
											List<NameValuePair> params1 = new ArrayList<NameValuePair>();
											params1.add(new BasicNameValuePair("cardInfo.userId", userId + ""));
//											card_number_tv = (TextView)view.findViewById(R.id.card_number_tv);
//											card_number_tv.setText(card_number);
											params1.add(new BasicNameValuePair("cardInfo.cardNumber", card_number));
											new DataLoader(CardAndAccountActivity.this).DisplayData(MainConstants.HOST_test
													+ HttpConfigAPI.REPORT_LOST_CARD, params1, handler2, "", false);
											showProgress("正在加载数据...");
										}else{
											showToast("该卡不能挂失");
										}
									}
								}
							}
						}
					});

			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface arg0,
								int arg1) {
						}
					});

			builder.create().show();
			
			break;
		case R.id.recharge_goto:
			if(null != cardInfos){
				for(CardInfo cardInfo : cardInfos){
					if(card_number == cardInfo.getCardNumber()){
						if("2".equals(cardInfo.getState())){
							Intent intent = new Intent(this,RechargeActivity.class);
							intent.putExtra("comeFromWhichActivity", "CardAndAccountActivity");
							intent.putExtra("card_number", card_number);
							startActivityForResult(intent, CardAndAccountActivity.RECHARGE);
						}else{
							showToast("该卡不能充值");
						}
					}
				}
			}
			break;
		default:
			break;
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(null != data){
//			chooseed_credits = data.getStringExtra("chooseed_credits");
			downLoadCardInfos();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	private class MyOnItemSelectedListener implements OnItemSelectedListener{

		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			if(null == cardInfos){
				cardInfos= application.getCardInfoList();
			}
			cardInfo = cardInfos.get(position);
			if("2".equals(cardInfo.getState())){
				rl_recharge_goto.setVisibility(View.VISIBLE);
				rl_reissue_card_goto.setVisibility(View.VISIBLE);
			}else{
				rl_recharge_goto.setVisibility(View.GONE);
				rl_reissue_card_goto.setVisibility(View.GONE);
			}
			card_number = cardInfo.getCardNumber();
			card_account_list = (ListView)CardAndAccountActivity.this.findViewById(R.id.card_account_list);
			if(null != cardInfo.getAccountList()){
				card_account_list.setAdapter(new CardAccountListAdapter(cardInfo.getAccountList(), CardAndAccountActivity.this));
				UtilListView.setListViewHeightBasedOnChildren(card_account_list);
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
			
		}

	}
	
	
}
